﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using DotNet.Model;
using DotNet.Business;
using DotNet.Common;
using System.Text;
public partial class Admin_FileDownLoad_selectRole : System.Web.UI.Page
{
    #region 初始化    
    int selectIndex = 0;
    int pageSize = 10;
    public string input = "<input id='HiddenUrl' type='hidden' value='&CurrentIndex=1'/>";


    userRoleBll urBll = new userRoleBll();
    roleBll rBll = new roleBll();
    PowerBll pBll = new PowerBll();
    rolePowerBll rpBll = new rolePowerBll();
    public string roleStr = "";
    ResourceBll resourceBll = new ResourceBll();
    resourceClassBll rcBll = new resourceClassBll();
    productResourceBll prBll = new productResourceBll();
    productClassBll pcBll = new productClassBll();
    productBll proBll = new productBll();
    ProgramBll programBll = new ProgramBll();
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        { 
            
        #region 处理管理员所拥有的角色
        if (Request.QueryString["adminId"] != null)
        {
            IList<role> list = rBll.GetModel();
            foreach (role r in list)
            {
                ListItem item = new ListItem();
                item.Text = r.Rolename;
                item.Value = r.Roleid.ToString();
                this.RadioButtonList1.Items.Add(item);
            }
            userRole ur = urBll.GetModelByAdminId(Convert.ToInt32(Request.QueryString["adminId"].Trim()));
            this.RadioButtonList1.SelectedValue = ur.Roleid.ToString();
            ViewState["ur"] = ur;
        }
        #endregion

        #region 处理角色所拥有的权限
        if (Request.QueryString["roleId"] != null)
        {
            this.SaveRolePowerBtn.Visible = true;
            IList<power> plist = pBll.GetModel();
            rolePower rp = rpBll.GetModelByRoleId(Convert.ToInt32(Request.QueryString["roleId"]));
            ViewState["rp"] = rp;
            if (rp.PowerId != null)
            {
                IList<string> strid = rp.PowerId.Split('|');
                foreach (power p in plist)
                {
                    ListItem li = new ListItem();
                    li.Text = p.Powername;
                    li.Value = p.PowerId.ToString();
                    if (strid.Contains(li.Value))
                    {
                        li.Selected = true;
                    }
                    this.CheckBoxList1.Items.Add(li);
                }
            }
            else
            {
                foreach (power p in plist)
                {
                    ListItem li = new ListItem();
                    li.Text = p.Powername;
                    li.Value = p.PowerId.ToString();
                    this.CheckBoxList1.Items.Add(li);
                }
            }


        }
        #endregion      

        #region 处理资源
        if (Request.QueryString["productId"]!=null)
        {            
            bindResourceClass();
            this.Panel1.Visible = true;
            this.pid_hid.Value = Request.QueryString["productId"];
            this.type_hide.Value = Request.QueryString["type"];
        }
        if (Request.QueryString["action"]!=null)
        {
            int rcid = Convert.ToInt32(Request.QueryString["ClassId"]);
            selectIndex = rcid;
            int pid = Convert.ToInt32(Request.QueryString["productId"]);
            bindResource(rcid, pid);
            this.pid_hid.Value = Request.QueryString["productId"];
            this.type_hide.Value = Request.QueryString["type"];
        }
        #endregion  

        #region 处理项目方案

        if (Request.QueryString["programId"]!=null)
        {
            this.Panel2.Visible = true;
            this.pid_hid.Value = Request.QueryString["programId"];            
           
        }

        if (Request.QueryString["action_program"]!=null)
        {
            int programId=0;
            if (Request.QueryString["programId"] != "")
            {
                 programId = Convert.ToInt32(Request.QueryString["programId"]);
                 this.pid_hid.Value = programId.ToString();
            }
            int productClassId = Convert.ToInt32(Request.QueryString["productClassId"]);
            if (productClassId!=0)
            {
                selectIndex = productClassId;
                bindProduct(programId, productClassId);   
            }           
        }
        #endregion

    }
}

    #region 角色的单选框
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
          string id=(sender as RadioButtonList).SelectedValue;
          userRole ur =new userRole();
          if ((ViewState["ur"] as userRole).Roleid != 0)
          {
              int userRoleId = (ViewState["ur"] as userRole).Userroleid;
              ur.Adminid = Convert.ToInt32(Request.QueryString["adminId"]);
              ur.Roleid = Convert.ToInt32(id);
              ur.Userroleid = userRoleId;
              if (urBll.Update(ur))
              {
                  ClientScript.RegisterClientScriptBlock(GetType(), "key", "<script type=\"text/javascript\"> parent.location.reload()</script>");
              }
          }
          else
          {
              ur.Adminid = Convert.ToInt32(Request.QueryString["adminId"]);
              ur.Roleid =Convert.ToInt32(this.RadioButtonList1.SelectedValue);
              if (urBll.Insert(ur))
              {
                  ClientScript.RegisterClientScriptBlock(GetType(), "key", "<script type=\"text/javascript\"> parent.location.reload()</script>");
              }
            
          }
      }
    #endregion

    #region 资源下拉框
      public string bindResourceClass() 
    {
        string classDp = "";       
        IList<resourceClass> rcList = rcBll.GetModel();
        classDp= "<option value=\"0\">--未选择--</option>";
        foreach (resourceClass rc in rcList)
        {
            if (rc.ResourceClassID == selectIndex)
            {
                classDp += "<option title=\"" + rc.ResourceClassID + "\" selected=\"selected\" value=\"" + rc.ResourceClassID + "\">" + rc.ResourceClassName + "</option>";
            }
            else
            {
                classDp += "<option title=\"" + rc.ResourceClassID + "\" value=\"" + rc.ResourceClassID + "\">" + rc.ResourceClassName + "</option>";
            }
        }
        return classDp;
    }
      #endregion

    #region 保存角色
    /// <summary>
    ///  保存角色
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SaveRolePowerBtn_Click(object sender, EventArgs e)
    {
        ListItemCollection lic = CheckBoxList1.Items;
        string powerId = "";
        foreach (ListItem li in lic)
        {
            if (li.Selected)
            {
                powerId += li.Value + "|";
            }
        }
        if(powerId.Length>0)
        powerId = powerId.Remove(powerId.Length - 1, 1);
        rolePower rp=new rolePower();
        if ((ViewState["rp"] as rolePower).RolePowerId != 0)
        {
          
            rp.RolePowerId=(ViewState["rp"] as rolePower).RolePowerId;
            rp.RoleId=Convert.ToInt32(Request.QueryString["roleId"]);
            rp.PowerId=powerId;
            if (rpBll.Update(rp)) 
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "key", "<script type=\"text/javascript\"> parent.location.reload()</script>");
            }
        }
        else
        {
            rp.RoleId=Convert.ToInt32(Request.QueryString["roleId"]);
            rp.PowerId=powerId;
            if (rpBll.Insert(rp))
            {
                ClientScript.RegisterClientScriptBlock(GetType(), "key", "<script type=\"text/javascript\"> parent.location.reload()</script>");
                
            }
        }
    }
      #endregion

    #region  保存资源按钮 ---郑同飞
    /// <summary>
    ///保存资源按钮 ---郑同飞
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void saveResource_btn_Click(object sender, EventArgs e)
    {           
        productResource pr = ViewState["productResource"] as productResource;
        IList<string> addResource = new List<string>();
        IList<string> delResource = new List<string>();
        string newResource = "";
        foreach (ListItem li in CheckBoxList2.Items)
        {
            if (li.Selected)
            {
                addResource.Add(li.Value);
            }
            else 
            {
                delResource.Add(li.Value);
            }
        }                   
        IList<string> resourceList = pr.ResourceID.Split('|');
        foreach (string str in addResource)
        {
            if (!resourceList.Contains(str)&&str!="")
            {
                newResource += str+"|";
            }              
        }                 
        foreach (string str in resourceList)
        {
            if (!delResource.Contains(str) && str != "")
            {
                newResource +=str+ "|";
            }
        }
        if (newResource.Contains("|"))
        {
            newResource = newResource.Remove(newResource.LastIndexOf('|'));
        }       
        if (pr.ProductResourceID== 0)
        {
            pr.ProductID = Convert.ToInt32(this.pid_hid.Value);
            pr.ResourceID = newResource;
            pr.resourceType =Convert.ToInt32(this.type_hide.Value);           
            prBll.Insert(pr);
        }
        else 
        {
            pr.ResourceID = newResource;
            pr.resourceType = Convert.ToInt32(this.type_hide.Value);
            prBll.Update(pr);
        }
        Response.Write("<script>location.href=location.href</script>");            
    }
    #endregion
      
    #region 绑定资源
    /// <summary>
    /// 资源类别绑定时，添加该资源类别下的资源
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void bindResource(int rcid,int pid)
    {
        if (rcid!=0)
        {
            int id = rcid;
            selectIndex = rcid;
            productResource pr = prBll.getModelByProductId(pid, Convert.ToInt32(Request.QueryString["type"]));
            ViewState["productResource"] = pr;
            IList<string> strResourceId = new List<string>();
            if (pr.ResourceID != null)
            {
                strResourceId = pr.ResourceID.Split('|');
            }
            if (Request.QueryString["CurrentIndex"] != null)
            {
                _currentIndex = Convert.ToInt32(Request.QueryString["CurrentIndex"]);
            }
            if (Request.QueryString["ClassId"] != null)
            {
                _classid = Convert.ToInt32(Request.QueryString["ClassId"]);
            }
            if (Request.QueryString["key"] != null)
            {
                _key = Server.HtmlDecode(Request.QueryString["key"].ToString());
            }
            DataTable dt = resourceBll.pageingForResource(_currentIndex, pageSize, _classid, _key);
            input = "<input id='HiddenUrl' type='hidden' value='&CurrentIndex=" + _currentIndex + "&ClassId=" + _classid + "&key=" + _key + "' />";
            IList<Resource> Resources = DotConvert.GetList<Resource>(dt);
            foreach (Resource R in Resources)
            {
                ListItem li = new ListItem();
                li.Text = R.ResourceName;
                li.Value = R.ResourceID.ToString();
                foreach (string rid in strResourceId)
                {
                    if (li.Value == rid)
                    {
                        li.Selected = true;
                    }
                }
                CheckBoxList2.Items.Add(li);
            }
            this.CheckBoxList2.DataBind();
            CheckBoxList2.ControlStyle.CssClass = "width: 100px; text-align:center;valign:top";
        }       
    }
    #endregion
        
    #region 分页按钮---郑同飞
    public void htmlPaging()
    {
        if (Request.QueryString["ClassId"] != null&&Request.QueryString["ClassId"]!="0")
        {
            string str = null;
            int count = 0;
            count = resourceBll.getRecordCount(_classid, _key);
            int pcount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            str = "页次：" + _currentIndex + "/" + pcount + "  每页" + pageSize + " 总收录数据" + count + "条";
            str += HtmlControls.pagIng(_currentIndex, pcount, "selectRole.aspx?action=bind&type=0&productId=" + this.pid_hid.Value + "&ClassId=" + _classid + "&key=" + Server.UrlEncode(_key) + "&CurrentIndex", "pageaa", "pagecurrent");
            Response.Write(str);
        }

    }
    #endregion

    #region 状态维护属性---郑同飞
    public int _currentIndex = 1;
    public int _classid = 0;
    public string _key = "";
    #endregion

    #region 产品类别下拉框    
    public string ProductClassDp(string name)
    {
        StringBuilder str = new StringBuilder();
        str.Append("<select onchange=\"bindProduct()\" name='selectDp' id='" + name + "' style='width:192px;'>");
        str.Append("<option value='0'>---顶级分类---</option>");
        str.Append(AddItems(0, 0, new StringBuilder()));
        str.Append("</select>");
        return str.ToString();
    }

    public string AddItems(int ParentID, int length, StringBuilder sb)
    {
        DataView dvTree = pcBll.GetDataView(pcBll.GetDataTable(), ParentID);
        length++;
        foreach (DataRowView row in dvTree)
        {
            if (selectIndex ==Convert.ToInt32(row["pClassId"]))
            {
                string str = addtab(length);
                sb.AppendFormat("<option selected=\"selected\" value='" + row["pClassId"].ToString() + "'>{0}</option>", str + "|--" + row["pClassName"].ToString());
                AddItems(Convert.ToInt32(row["pClassId"].ToString()), length, sb);
            }
            else
            {
                string str = addtab(length);
                sb.AppendFormat("<option value='" + row["pClassId"].ToString() + "'>{0}</option>", str + "|--" + row["pClassName"].ToString());
                AddItems(Convert.ToInt32(row["pClassId"].ToString()), length, sb);
            }
        }
        return sb.ToString();
    }
    private string addtab(int i)
    {
        string mark = "&nbsp;";
        if (i != 1)
        {
            for (int j = 0; j < i - 1; j++)
            {

                mark += "&nbsp;&nbsp;&nbsp;&nbsp;";
            }
        }
        return mark;
    } 
    #endregion

    #region 绑定产品
    public void bindProduct(int programId,int productClassId) 
    {
        IList<product> productList =DotConvert.GetList<product>(proBll.pagingForProduct(1,100,productClassId,""));
        Program programModel = programBll.GetModel(programId);
        programModel.programId = programId;
        IList<string> pList = new List<string>();
        ViewState["programModel"] = programModel;
        if (programModel.productID!=""&&programModel.productID!=null)
        {
           pList = programModel.productID.Split('|');
        }
        foreach (product pro in productList)
        {
            ListItem li = new ListItem();
            li.Text = pro.productName;
            li.Value = pro.productId.ToString();
            foreach (string str in pList)
            {
                if (li.Value == str)
                {
                    li.Selected = true;
                }
            }
            CheckBoxList3.Items.Add(li);
        }
        CheckBoxList3.DataBind();        
    }
    #endregion

    protected void Button2_Click(object sender, EventArgs e)
    {
        Program programModel = ViewState["programModel"] as Program;
        IList<string> addProduct = new List<string>();
        IList<string> delProduct = new List<string>();
        string newProduct = "";
        foreach (ListItem li in CheckBoxList3.Items)
        {
            if (li.Selected)
            {
                addProduct.Add(li.Value);
            }
            else
            {
                delProduct.Add(li.Value);
            }
        }
        IList<string> productList = programModel.productID.Split('|');
        foreach (string str in addProduct)
        {
            if (!productList.Contains(str) && str != "")
            {
                newProduct += str + "|";
            }
        }
        foreach (string str in productList)
        {
            if (!delProduct.Contains(str) && str != "")
            {
                newProduct += str + "|";
            }
        }
        if (newProduct.Contains("|"))
        {
            newProduct = newProduct.Remove(newProduct.LastIndexOf('|'));
        }
        if(programModel.programId != 0)
        {
            programModel.productID = newProduct;
            programBll.Update(programModel);
            Response.Write("<script language='javascript'>alert('添加成功！');window.parent.document.getElementById('product_hid').value='" + newProduct + "';</script>");
        }
    }
}
